//
//  EmoticonKBView.swift
//  emoticonKB
//
//  Created by mac on 16/3/19.
//  Copyright © 2016年 mac. All rights reserved.
//

import UIKit
import SnapKit

private var EmoticonCellId  = "EmoticonCellId"
class EmoticonKBView: UIView {

    var packages = EmoticonManager.sharedEmoticonManager.packages

    //重写构造方法
     init() {
        //系统键盘默认高度是226 6Plus 6SPlus 其他手机默认 216
        
        let frame = CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: 220)
        super.init(frame: frame)
        setupUI()
    }
    //默认实现报错
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //MARK: 设置UI界面
    private func setupUI() {
    
        addSubview(toolBar)
        addSubview(collectionView)
        addSubview(pageControl)
        
        //设置约束
        toolBar.snp_makeConstraints { (make) -> Void in
            make.right.left.bottom.equalTo(self)
            make.height.equalTo(36)
        }
        collectionView.snp_makeConstraints { (make) -> Void in
            make.left.right.top.equalTo(self)
            make.bottom.equalTo(toolBar.snp_top)
        }
        
        pageControl.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self)
            make.bottom.equalTo(toolBar.snp_top).offset(-5);
        }
        
        toolBar.emoticonBtnClick = { (index: Int) -> () in
            
            // 点击某个按钮 集合视图跳转到对应的section
            let indexPath = NSIndexPath(forItem: 0, inSection: index)
            self.collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: true)
        }
        
        //首次进入时候更新
        updatePageControlData(NSIndexPath(forItem: 0, inSection: 0))
        
    }
    //设置itemsize  系统布局完成后 再设置itemsize
    override  func layoutSubviews() {
        super.layoutSubviews()
        let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = collectionView.bounds.size
        
    }
 
    //懒加载创建子视图
    private lazy var toolBar: EmoticonToolBar = EmoticonToolBar()
    
    private lazy var pageControl: UIPageControl = {
        let pageControl = UIPageControl()
// _pageImage  _currentPageImage  在Xcode 6.4之前的版本是可以看到对应的带下划线的成员变量
        
//        pageControl.pageIndicatorTintColor = UIColor.blueColor()
//        pageControl.currentPageIndicatorTintColor = UIColor.redColor()
        
        pageControl.setValue(UIImage(named: "compose_keyboard_dot_normal"), forKey: "_pageImage")
        pageControl.setValue(UIImage(named: "compose_keyboard_dot_selected"), forKey: "_currentPageImage")
        
        return pageControl
        }()
    
    //图片视图
    private lazy var collectionView: UICollectionView = {
    
        let layout = UICollectionViewFlowLayout()
        
        //设置itemsize 此处不能获取到结合视图的大小

        //设置滚动方向 和左右间距
        layout.scrollDirection = .Horizontal
        
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        
        let cv = UICollectionView(frame: CGRectZero, collectionViewLayout: layout)
        
        //设置分页滚动 collectionView的属性
        cv.pagingEnabled = true
        cv.showsHorizontalScrollIndicator = false
        
        
        cv.dataSource = self
        cv.delegate = self
        
        cv.registerClass(EmoticonPageCell.self, forCellWithReuseIdentifier: EmoticonCellId)
 
        return cv
    }()
}

extension EmoticonKBView: UICollectionViewDataSource,UICollectionViewDelegate {

    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return packages.count

    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return packages[section].sectionEmoticon.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("EmoticonCellId", forIndexPath: indexPath) as! EmoticonPageCell
        
//        cell.indexPath = indexPath
        cell.emoticons = packages[indexPath.section].sectionEmoticon[indexPath.item]
        
//        cell.backgroundColor = indexPath.item % 2 == 0 ? UIColor.redColor() : UIColor.yellowColor()
        
        return cell
        
    }
    
    //减速结束之后会调用
//    func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
    
    //滚动就更新
    func scrollViewDidScroll(scrollView: UIScrollView) {
        //根据 sv的水平位移
        var center = scrollView.center
        //确定中心点
        center.x += scrollView.contentOffset.x
//可以判断当前屏幕中显示最多有两个cell 获取cell的frame 如果包含了cell中心点 就获取对应cell的indexPath
        let indexPaths = collectionView.indexPathsForVisibleItems()
        //遍历获取对应cell
        for indexPath in indexPaths {
            let cell = collectionView.cellForItemAtIndexPath(indexPath)!
            if cell.frame.contains(center){
                //显示分页指示
                updatePageControlData(indexPath)
            }
        }
//        let cv = scrollView as! UICollectionView
//        
//        //获取最后显示的cell
//        if let cell = cv.visibleCells().first {
//        
//            // 根据cell获取indexPath
//            let indexPath = cv.indexPathForCell(cell)
//            
//            //选中对应toolBar中的按钮
//            toolBar.selectButtonAtIndexPathOfSection(indexPath?.section ?? 0)
    }
    
    //更新分页数据
    private func updatePageControlData(indexPath: NSIndexPath) {
    
        pageControl.numberOfPages = EmoticonManager.sharedEmoticonManager.packages[indexPath.section].sectionEmoticon.count;
        pageControl.currentPage = indexPath.item;
    }
}


